<?php
/**
 * HX<titanrain@163.com>
 */
class BookService{

    public static function findById($id){
        return BookAR::detail($id);
    }
    
    public static function privateBookInfo($id = 0){
    	return UserBookAR::queryById($id,User::id());
    }
    
    public static function suggest($bookId,$type){
    	$book = DBUtil::row(BookAR::tblName(),array('book_id','book_name'),'book_id='.$bookId);
    	switch($type){
    		case 1:
    			$message = '本书无法下载';
    			break;
    		case 2:
    			$message = '本书未完结';
    			break;
    		case 3:
    			$message = '本图书和书名不符';
    	}
    	$data = array('book'=>$book,'message'=>$message,'e_type'=>$type);
    	return $data;
    }
    
    public static function obtainBook($bookId){
    	$props = array('book_id','book_name','book_size','book_path','book_pic','book_md5');
    	$tmp = DBUtil::row(BookAR::tblName(),$props,'book_id='.$bookId);
    	if($tmp['book_pic']==''){
    		$tmp['book_pic'] = '/images/no_book_pic.jpg';
    	}
    	return $tmp;
    }
    
    public static function publicBookInfo($id = 0){
    	$tmp = DBUtil::row(BookAR::tblName(),array('book_id','book_name','author','book_pic','book_desn'),'book_id='.$id);
    	if($tmp['book_pic']==''){
    		$tmp['book_pic'] = '/images/no_book_pic.jpg';
    	}
    	return $tmp;
    }

    public static function view($id = 0){
        FileUtil::appendClickedBookId($id);
		$book = BookAR::detail($id);
        if(!$book){
            return false;
        }
        $data['book'] = $book;
        //comment
        $data['comments'] = CommentAR::commentsOfBook($id);
        //other book of the author
        $data['author_otherbooks'] = BookAR::authorOtherBooks($id,$book['author']);
        return $data;
	}

    public static function searchBookAndAuthor($bookOrAuthor,$page){
        return BookAR::searchBook($bookOrAuthor,$page);
    }

	public static function download($id = 0){
		DownloadAR::persist(User::id(),$id);
		BookAR::increDownloadTimes($id);
		return BookAR::downloadInfo($id);
	}
	
	/**
	 * @param $bookNameByUser The book name writed by user
	 */
	public static function upload($bookNameByUser,$categoryId,$author,$bookDesn){
		//save file
		$bookInfo = FileUtil::uploadBook('book_file');
		if(!$bookInfo['success']){
			return array('success'=>false,'message'=>$bookInfo['message']);
		}
		$bookId = BookAR::queryByMD5($bookInfo['md5']);
		if($bookId){
			FileUtil::deleteBook($bookInfo['book_path']);
		} else {
            //book_pic book_desn,author
            $bookPic = FileUtil::uploadBookPic('book_pic');
			$bookId = BookAR::saveBook($bookNameByUser,$bookInfo,$categoryId,User::id(),User::name(),$author,$bookDesn,$bookPic);
		}
		//This book will be in user's personal library
		if(User::id() != 0){
            $bookNameByUser = $bookNameByUser == '' ? $bookInfo['origin_name'] : $bookNameByUser;
			$ok = UserBookAR::persist(User::id(),$bookId,$bookNameByUser,$categoryId);
            if(!$ok){
                return array('success'=>false,'message'=>'您已经上传过这本书了');
            }
            UserAR::increUploadTimes(User::id());
			//disk_used - $bookInfo['size']	
			UserAR::increDiskUsedAndDiskSize(User::id(),$bookInfo['size']);
            $genSize = DiskGenAR::forUpload(User::id(),User::name());
            UserAR::increDiskSize(User::id(),$genSize);
		}
		return array('success'=>true,'book_id'=>$bookId,'book_name'=>$bookNameByUser);
	}

    public static function batchUpload($user_id,$user_name,$field){
    	$categoryId = 3;
        $bookInfo = FileUtil::uploadBook($field);
		if(!$bookInfo['success']){
			return array('success'=>false,'message'=>$bookInfo['message']);
		}
		$bookId = BookAR::queryByMD5($bookInfo['md5']);
		if($bookId){
			FileUtil::deleteBook($bookInfo['book_path']);
		} else {
			$bookId = BookAR::saveBook('',$bookInfo,$categoryId,$user_id,$user_name,'','','');
		}
		//This book will be in user's personal library
		if($user_id != 0){
            $bookNameByUser = $bookInfo['origin_name'];
			$ok = UserBookAR::persist($user_id,$bookId,$bookNameByUser,$categoryId);
            if(!$ok){
                return array('success'=>false,'message'=>'您已经上传过这本书了');
            }
            UserAR::increUploadTimes($user_id);
			//disk_used - $bookInfo['size']	
			UserAR::increDiskUsedAndDiskSize($user_id,$bookInfo['size']);
            $genSize = DiskGenAR::forUpload($user_id,$user_name);
            UserAR::increDiskSize($user_id,$genSize);
		}
		return array('success'=>true,'book_id'=>$bookId,'book_name'=>$bookNameByUser);
    }
	
	public static function update($bookId,$author,$bookDesn){
		$bookPic = self::uploadBookPic('book_pic');
		return BookAR::updateBook($bookId,$author,$bookDesn,$bookPic);
	}
	
	private static function uploadBookPic($field = ''){
		$bookPic = '';
		if(isset($_FILES[$field])){
			$bookPic = FileUtil::uploadBookPic($field);
		}
		return $bookPic;
	}
	public static function userUpdateBook($bookId,$selectedCid,$priBookName,$pubBookName,$author,$bookDesn){
		$bookPic = self::uploadBookPic('book_pic');
		$userId = User::id();
		if($userId == 0){
			return;
		}
		$userBookProps = array('book_name'=>$priBookName,'fk_category'=>$selectedCid);
		DBUtil::update(UserBookAR::tblName(),$userBookProps,"fk_user=$userId and fk_book=$bookId");
		
		$bookProps = array();
		if($bookPic != ''){
			$bookProps['book_pic'] = $bookPic;
		}
		if($pubBookName != ''){
			$bookProps['book_name'] = $pubBookName;
		}
		if($author != ''){
			$bookProps['author'] = $author;
		}
		if($bookDesn != ''){
			$bookProps['book_desn'] = $bookDesn;
		}
		$post_data = array('book_id'=>$bookId,'book_name'=>$pubBookName,'book_pic'=>$bookPic,'sign'=>md5($bookId.'ccs8_cn'));
		MyUtil::postData('http://www.5show5.com/book/update.php','www.5show5.com',$post_data);
		
		DBUtil::update(BookAR::tblName(),$bookProps,"book_id=$bookId");
	}

    public static function statistics(){
        $checkedCount = BookAR::model()->count('book_status=1');
        $unCheckedCount = BookAR::model()->count('book_status=0');
        $noHandleCheckedCount = BookAR::model()->count('book_status=2');
        return array('checked'=>$checkedCount,'un_checked'=>$unCheckedCount,'no_handle_check'=>$noHandleCheckedCount);
    }
	
	public static function handleDiskUsedForUpload($userId,$bookSize){
		if(intval($userId) === 0){
			return;
		}
		UserAR::increDiskUsedAndDiskSize($userId,$bookSize);
	}
	
	public static function topNewUploadPage($cidAndPageno){
		$page = new Page($cidAndPageno['pageno'],Yii::app()->params['classPageSize']);
		return BookAR::topNewUploadPageByCid($cidAndPageno['cid'],$page);
	}
	
	public static function topDownload($limit = 10,$condition = array()){
		return BookAR::topDownload($limit,$condition);
	}
	
	public static function topClicked($limit = 10,$condition = array()){
		return BookAR::topClicked($limit,$condition);
	}
	
	public static function topComment($limit = 10,$condition = array()){
		return BookAR::topComment($limit,$condition);
	}
	
	public static function topNewUpload($limit = 10,$condition = array()){
		return BookAR::topNewUpload($limit,$condition);
	}
	
	public static function increClickedTimes($bookIdArr){
		$arr = array();
		foreach($bookIdArr as $bookId){
			if(array_key_exists($bookId,$arr)){
				$arr[$bookId] = $arr[$bookId] + 1;
			}else{
				$arr[$bookId] = 1;				
			}
		}
		foreach($arr as $bookId=>$clickTimes){
			BookAR::increClickedTimes($bookId,$clickTimes);
		}
	}
	public static function handleKeywords($lines){
		SearchAR::batchSave($lines);
	}
}
